﻿//===========================================================================================================================
// Cuberry - http://www.cuberry.net
// Copyright (c) 2012
// by Peacequare® - Amir Moussa
//===========================================================================================================================
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License 
// as published by the Free Software Foundation, either version 3 of the License, or any later version.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// This program is distributed in the hope that it will be useful.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//===========================================================================================================================

using System;
using System.Collections;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using System.Windows.Controls;
using P2.Cuberry.Framework.Helper;


namespace P2.Cuberry.Modules.Framework.UserGroup
{
    /// <summary>
    /// Interaction logic for UserGroupsDetailsView.xaml
    /// </summary>
    public partial class UserGroupsDetailsView : Window, IUserGroupsDetailsView
    {
        public UserGroupsDetailsView()
        {
            InitializeComponent();
        }


        public UserGroupsDetailsPresentationModel Model
        {
            get { return this.DataContext as UserGroupsDetailsPresentationModel; }
            set
            {
                if (value != null)
                {
                    this.DataContext = value;
                }
            }
        }


        private void PrintBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string myReportLocation = @".\Reports\PrintUserGroupsDetails" + P2Translator.CultureLanguageFU + ".rdlc";

                SortedList myDataSourceCollection = new SortedList();
                myDataSourceCollection.Add("UserGroup", this.Model.Model);

                P2ReportViewer myReportViewer = new P2ReportViewer(myReportLocation, myDataSourceCollection, "User Group Print");
                myReportViewer.Show();

            }
            catch (Exception ex) //AM:TC!!
            {
                ExceptionPolicy.HandleException(ex, "Default Policy");
                P2Validator.YellowErrorDialog.Confirm(P2Translator.GetResource("Report error"), ex.Message, null, null, null);
            }
        }


        public void CellFocusable(Object sender, RoutedEventArgs e)
        {
        }


        public void UpdateFocusedControl()
        {
            try
            {
                TextBox focusedTextBox = Keyboard.FocusedElement as TextBox;
                if (focusedTextBox == null)
                    return;

                BindingExpression textBindingExpr =
                  focusedTextBox.GetBindingExpression(TextBox.TextProperty);
                if (textBindingExpr == null)
                    return;

                textBindingExpr.UpdateSource();
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }


        private void UserGroupModuleList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
        }


        private void AccessButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Button senderButton = (Button)sender;
                var bkgBinding = senderButton.GetBindingExpression(Button.BackgroundProperty);
                if (bkgBinding != null)
                {
                    var dataItem = (BusinessEntities.UserGroupRight)bkgBinding.DataItem;
                    if (dataItem != null)
                    {
                        if (dataItem.ActiveColor == Brushes.Red)
                        {
                            dataItem.ActiveColor = Brushes.Yellow;
                        }

                        else if (dataItem.ActiveColor == Brushes.Yellow)
                        {
                            dataItem.ActiveColor = Brushes.Green;
                        }
                        else if (dataItem.ActiveColor == Brushes.Green)
                        {
                            dataItem.ActiveColor = Brushes.Red;
                        }
                        else
                        {
                            dataItem.ActiveColor = Brushes.Red;
                        }

                    }
                }
                else
                {
                    if (((Button)sender).Background == Brushes.Red)
                    {
                        ((Button)sender).Background = Brushes.Yellow;
                    }

                    else if (((Button)sender).Background == Brushes.Yellow)
                    {
                        ((Button)sender).Background = Brushes.Green;
                    }
                    else if (((Button)sender).Background == Brushes.Green)
                    {
                        ((Button)sender).Background = Brushes.Red;
                    }
                    else
                    {
                        ((Button)sender).Background = Brushes.Red;
                    }
                }
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }


        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.UserGroupName.GetBindingExpression(TextBox.TextProperty).UpdateSource();

            if (!this.Model.writeable)
            {
                this.UserGroupName.IsReadOnly = true;
            }
        }


        public bool AskSave()
        {
            try
            {
                UpdateFocusedControl();
                if (Model.NameEnabled)
                {
                    bool usergroupright_modified = false;
                    bool usergroupspecialright_modified = false;
                    foreach (BusinessEntities.UserGroupRight UserGroupRightItem in Model.UserGroupModuleList)
                    {
                        if (UserGroupRightItem.Modified) { usergroupright_modified = true; }
                        foreach (BusinessEntities.UserGroupSpecialRight UserGroupSpecialRightItem in UserGroupRightItem.UserGroupSpecialRightItems)
                        {
                            if (UserGroupSpecialRightItem.Modified) { usergroupspecialright_modified = true; }

                        }
                        if (UserGroupRightItem.UserGroupSpecialRightDeletedItems != null && UserGroupRightItem.UserGroupSpecialRightDeletedItems.Count > 0)
                            usergroupspecialright_modified = true;
                    }

                    if (Model.ModelIsModified || usergroupright_modified || usergroupspecialright_modified)
                    {
                        MessageBoxOptions opt = MessageBoxOptions.None;
                        if (this.FlowDirection == FlowDirection.RightToLeft) opt = MessageBoxOptions.RtlReading;
                        MessageBoxResult result = MessageBox.Show(P2Translator.GetResource("UserGroupNotSaved"), P2Translator.GetResource("UserGroupNotSavedCaption"), MessageBoxButton.YesNoCancel, MessageBoxImage.Exclamation, MessageBoxResult.Cancel, opt);

                        switch (result)
                        {
                            case MessageBoxResult.Cancel:
                                break;
                            case MessageBoxResult.No:
                                Model.Cancel();
                                return true;
                            case MessageBoxResult.Yes:
                                Model.Save();
                                if (StatusStrip.Status == "green")
                                    return true;
                                break;
                            default:
                                break;
                        }
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
                return true;
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
                return false;
            }
        }


        public bool YellowStatusWarning(string MessageText, string CaptionText)
        {
            MessageBoxOptions opt = MessageBoxOptions.None;
            if (this.FlowDirection == FlowDirection.RightToLeft) opt = MessageBoxOptions.RtlReading;
            MessageBoxResult result = MessageBox.Show(MessageText, CaptionText, MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.Cancel, opt);

            switch (result)
            {
                case MessageBoxResult.Cancel:
                    break;
                case MessageBoxResult.No:
                    return false;
                    break;
                case MessageBoxResult.Yes:
                    return true;
                    break;
                default:
                    break;
            }
            return false;
        }


        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = !this.AskSave();
        }


        private void UserGroupModuleList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                BusinessEntities.UserGroupRight ur = (BusinessEntities.UserGroupRight)UserGroupModuleList.SelectedItem;
                this.Model.UserGroupSpecialRightsList = ur.UserGroupSpecialRightItems;
                UserGroupSpecialRightsListD.InvalidateVisual();
                UserGroupSpecialRightsListD.GetBindingExpression(System.Windows.Controls.DataGrid.ItemsSourceProperty).UpdateTarget();
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }


        public event EventHandler<DataEventArgs<BusinessEntities.UserGroupRight>> UserGroupSpecialRightOpened = delegate { };


        private void UserGroupSpecialRightAddBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if ((BusinessEntities.UserGroupRight)UserGroupModuleList.SelectedItem == null)
                {
                    this.Model.MessageStack.Add(new P2TransactionMessage(P2ValidationStatus.yellow, P2Translator.GetResource("TMsg_Entityschouldbechoosed")));
                }
                else
                {
                    BusinessEntities.UserGroupRight ur = (BusinessEntities.UserGroupRight)UserGroupModuleList.SelectedItem;
                    BusinessEntities.UserGroupRight newItem = ur.GetCopy();
                    UserGroupSpecialRightOpened(this, new DataEventArgs<P2.Cuberry.Modules.Framework.UserGroup.BusinessEntities.UserGroupRight>(ur));
                    ur.FillMyObject();
                    ur.OnAllPropertiesChanged();
                }
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }


        private void UserGroupSpecialRightsList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (UserGroupSpecialRightsListD.SelectedItem != null)
            {
                BusinessEntities.UserGroupRight ur = (BusinessEntities.UserGroupRight)UserGroupModuleList.SelectedItem;
                BusinessEntities.UserGroupRight newItem = ur.GetCopy();
                UserGroupSpecialRightOpened(this, new DataEventArgs<P2.Cuberry.Modules.Framework.UserGroup.BusinessEntities.UserGroupRight>(ur));
            }
        }


        private void UserGroupSpecialRightDeleteBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                BusinessEntities.UserGroupRight ur = (BusinessEntities.UserGroupRight)UserGroupModuleList.SelectedItem;
                BusinessEntities.UserGroupSpecialRight usr = (BusinessEntities.UserGroupSpecialRight)UserGroupSpecialRightsListD.SelectedItem;
                ur.UserGroupSpecialRightItems.Remove(usr);
                UserGroupSpecialRightsListD.GetBindingExpression(System.Windows.Controls.DataGrid.ItemsSourceProperty).UpdateTarget();
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }


    }
}
